require('dotenv').config();
const Imap = require('node-imap');
const { simpleParser } = require('mailparser');
const fs = require('fs');

const mailConfig = {
    user: process.env.EMAIL,
    password: process.env.PASSWORD,
    host: process.env.IMAP_HOST,
    port: process.env.IMAP_PORT,
    tls: true,
    tlsOptions: { rejectUnauthorized: false }
};

const imap = new Imap(mailConfig);

function processEmail(mail, seqNum) {
    console.log(`Processing email #${seqNum}`);
    let mailContent = '';
    
    mail.on('body', stream => {
        stream.on('data', chunk => {
            mailContent += chunk.toString('utf8');
        });

        stream.once('end', () => {
            simpleParser(mailContent, async (err, parsed) => {
                if (err) {
                    console.error('Parse mail failed:', err);
                    return;
                }
                console.log('------------------------');
                console.log('Subject:', parsed.subject);
                console.log('From:', parsed.from.text);
                console.log('Date:', parsed.date);
                console.log('Has attachments:', parsed.attachments?.length > 0);
                console.log('Content:', parsed.text ? parsed.text.substring(0, 200) + '...' : 'No text content');
                
                if (parsed.attachments?.length > 0) {
                    console.log(`Found ${parsed.attachments.length} attachments`);
                    if (!fs.existsSync('./attachments')) {
                        fs.mkdirSync('./attachments');
                    }
                    
                    parsed.attachments.forEach(attachment => {
                        try {
                            console.log('------------------------');
                            console.log('Attachment details:');
                            console.log('Filename:', attachment.filename);
                            console.log('Content Type:', attachment.contentType);
                            console.log('Size:', attachment.size, 'bytes');
                            
                            // 确保文件名包含扩展名
                            let filename = attachment.filename;
                            // 如果文件名中没有扩展名，根据 contentType 添加
                            if (!filename.includes('.')) {
                                const ext = attachment.contentType.split('/')[1];
                                filename = `${filename}.${ext}`;
                            }
                            
                            const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
                            const filePath = `./attachments/${timestamp}_${filename}`;
                            fs.writeFileSync(filePath, attachment.content);
                            console.log('Saved to:', filePath);
                        } catch (error) {
                            console.error('Error saving attachment:', error);
                        }
                    });
                }
            });
        });
    });

    mail.once('end', () => {
        console.log(`Finished processing email #${seqNum}`);
    });
}

function fetchMails(mailIds) {
    console.log(`Found ${mailIds.length} emails`);
    
    const fetch = imap.fetch(mailIds, {
        bodies: '',
        struct: true,
        markSeen: false
    });

    fetch.on('message', processEmail);
    fetch.once('error', err => console.error('Fetch mail failed:', err));
    fetch.once('end', () => {
        console.log('All mails processed');
        imap.end();
    });
}

imap.once('ready', () => {
    imap.openBox('INBOX', false, (err, box) => {
        if (err) {
            console.error('Open inbox failed:', err);
            return;
        }

        // 修改搜索范围为最近30天
        const thirtyDaysAgo = new Date();
        thirtyDaysAgo.setDate(thirtyDaysAgo.getDate());
        imap.search([['SINCE', thirtyDaysAgo.toISOString()]], (err, recentMails) => {
            if (err || recentMails.length === 0) {
                console.log('No recent emails found, fetching last 10 emails');
                imap.sort(['ARRIVAL'], ['ALL'], (err, allMails) => {
                    if (err) {
                        console.error('Get mails failed:', err);
                        return;
                    }
                    // 获取最新的10封邮件而不是5封
                    fetchMails(allMails.slice(-10));
                });
                return;
            }
            console.log(`Found ${recentMails.length} recent emails`);
            fetchMails(recentMails);
        });
    });
});

imap.once('error', err => console.error('IMAP error:', err));
imap.once('end', () => console.log('Connection closed'));

imap.connect();